import { Message } from 'element-ui';
import { getExplorer, getIEVersion, isMobile } from '@/utils/tools';
import { openNewWindow } from '@/utils/index';
// import { ddAutoLogin } from '@/utils/dingtalkAutologin';

import store from '@/store';
const { ddAppID, feishuAppId, NODE_ENV } = process.env;
const config = {
  homeName: 'Index', // 需要跳转地址或HOME
  ddAppID: ddAppID,
  feishuAppId: feishuAppId
};

/**
 * 钉钉登录Mixin
 * 放置二维码的区域请设置id="login_dd_code_container"，
 * 在需要使用的页面调用changeDDCode()初始化，
 * 即可扫码登录后自动跳转主页
 */
export default {
  data() {
    return {
      isInitCode: false,
      isInitFeishuCode: false,
      feishuQRLoginObj: null,
      ddLoginUrl: '',
      feishuLoginUrl: '',
      currentExplorer: '',
      currentIEVersion: ''
    };
  },
  computed: {
    isInDingTalk() {
      if (this.$route.query.isInDingTalkTest === '1') return true;
      return this.currentExplorer === 'DingTalk';
    },
    isInFeishu() {
      return this.currentExplorer === 'Feishu';
    },
    isInPCDingTalk() {
      return this.currentExplorer === 'DingTalk' && !isMobile();
    },
    isMobile() {
      return isMobile();
    }
  },
  beforeRouteEnter(to, from, next) {
    // 这里不能使用this，尚未初始化
    // 判断是不是钉钉登录后返回，并防止重放攻击
    const ddNotLoginState = localStorage.getItem('ddNotLoginState');
    const ddHadLoginState = localStorage.getItem('ddHadLoginState');
    const query = new URLSearchParams(location.search || '?');
    const loginredirect = query.get('loginredirect'); // 重定向
    console.log('loginredirect', loginredirect);
    let redirect = query.get('redirect');
    const ddCode = query.get('code'); // 适配去除'?code='
    const ddState = query.get('state');
    const isFeishuLogin = ddState && ddState.indexOf('feishu') >= 0;
    let url = `${location.origin}`;
    url = url.replace(/\/$/, '');
    const CACHE_REDIRECT_URI = localStorage.getItem('CACHE_REDIRECT_URI') || url;
    localStorage.removeItem('CACHE_REDIRECT_URI');
    if (ddCode && (ddState === ddNotLoginState || ddState !== ddHadLoginState)) {
      localStorage.removeItem('ddNotLoginState');
      localStorage.setItem('ddHadLoginState', ddState);
      const currentExplorer = getExplorer() || window.navigator.userAgent;
      if (currentExplorer === 'DingTalk' && !isMobile()) {
        Message.info('正在打开外部浏览器！');
        let path = '';
        let redirectParams = '';
        if (redirect) {
          for (const [key, value] of query.entries()) {
            if (key !== 'redirect' && key !== 'code' && key !== 'state' && value) {
              // redirect += `${redirect.indexOf('?') < 0 ? '?' : '&'}${key}=${value}`;
              redirectParams += `&${key}=${value}`;
            }
          }
          path = '&redirect=' + redirect;
        } else if (loginredirect) {
          redirectParams += `&loginredirect=${loginredirect}`;
        }
        openNewWindow(location.origin + '?code=' + ddCode + '&state=' + ddState + redirectParams + path);
        setTimeout(() => { location.href = `/?redirect=${redirect}`; }, 500);
        return;
      }
      localStorage.setItem('loginCode', ddCode);
      const loginParams = {
        code: ddCode, queryParams: CACHE_REDIRECT_URI
      };
      if (isFeishuLogin) {
        const feishuAutoLogin = ddState && ddState.indexOf('autoLogin') >= 0;
        console.log('feishuAutoLogin', feishuAutoLogin);
        if (feishuAutoLogin) loginParams.autoLogin = true;
        if (ddState && ddState.indexOf('-extensions') >= 0) {
          return;
        }
      }
      store.dispatch(isFeishuLogin ? 'FeishuLogin' : 'DingLogin', loginParams).then(() => { // 获取到code后进行登录服务
        Message.success(`${isFeishuLogin ? '飞书' : '钉钉'}登录成功！`);
        console.log('登录成功loginredirect', loginredirect);
        if (redirect) {
          for (const [key, value] of query.entries()) {
            if (key !== 'redirect' && key !== 'code' && key !== 'state' && value) {
              redirect += `${redirect.indexOf('?') < 0 ? '?' : '&'}${key}=${value}`;
            }
          }
          next(redirect ? { path: decodeURIComponent(redirect) } : { name: config.homeName }); // 需要跳转地址或HOME
        } else if (loginredirect) {
          try {
            const params = JSON.parse(decodeURIComponent(loginredirect));
            next(params || { name: config.homeName });
          } catch (error) {
            next({ name: config.homeName });
          }
        } else {
          next({ name: config.homeName });
        }

        localStorage.removeItem('loginCode');
        sessionStorage.removeItem('isShowTips');
      }).catch((e) => {
        // alert(JSON.stringify('err'));
        console.error(e);
        if (Number(e.code) === 513) e.msgLevel = 99; // 钉钉登录失败
        Message.error((e.msgLevel && e.message) || `${isFeishuLogin ? '飞书' : '钉钉'}登录失败，请重新登录！`);
        localStorage.removeItem('loginCode');
        setTimeout(() => {
          next(redirect || { name: to.name });
        }, 1500);
        sessionStorage.setItem('isShowTips', true);
      });
      return;
    } else if (ddCode || ddState) {
      query.delete('code');
      query.delete('state');
      query.delete('dd_orientation'); // pad中不去掉，在钉钉里会打开多次标签
      location.href = `${location.origin}${location.pathname}?${query.toString()}${location.hash ? `/${location.hash}` : ''}`;
    }
    // 通过钉钉点击进入，执行免登鉴权
    // ddAutoLogin().then((code) => {
    //   store.dispatch('DingLogin', { code }).then(() => { // 获取到code后进行登录服务
    //     Message.success('钉钉登录成功！');
    //     next(redirect ? { path: decodeURIComponent(redirect) } : { name: config.homeName }); // 需要跳转地址或HOME
    //   }).catch((e) => {
    //     console.error(e);
    //     if (Number(e.code) === 513) e.msgLevel = 99; // 钉钉登录失败
    //     Message.error((e.msgLevel && e.message) || '钉钉登录失败，请重新登录！');
    //     next(redirect || { name: to.name });
    //   });
    //   return;
    // });
    next();
  },
  created() {
    // 事件绑定
    if (typeof window.addEventListener !== 'undefined') { // 标准浏览器
      window.addEventListener('message', this.onHandleMsg, false);
    } else if (typeof window.attachEvent !== 'undefined') { // IE浏览器
      window.attachEvent('onmessage', this.onHandleMsg);
    }

    this.currentExplorer = getExplorer() || window.navigator.userAgent;
    this.currentIEVersion = getIEVersion();
    // console.info('ddLogin', this.currentExplorer, this.currentIEVersion);
    // if (this.currentExplorer === 'DingTalk' && (!store.state.user.token || store.state.user.token === '')) {
    //   this.createRedirectURI('autoLogin');
    //   location.href = this.ddLoginUrl;
    // }
  },
  beforeDestroy() {
    // 事件解绑
    if (typeof window.removeEventListener !== 'undefined') {
      window.removeEventListener('message', this.onHandleMsg);
    } else if (typeof window.detachEvent !== 'undefined') {
      window.detachEvent('onmessage', this.onHandleMsg);
    }
  },
  methods: {
    createRedirectURI(isAuto = 0) {
      const APPID = config.ddAppID;

      const SCOPE = isAuto ? 'snsapi_auth' : 'snsapi_login';
      const STATE = new Date().getTime();
      localStorage.setItem('ddNotLoginState', STATE);

      // // const REDIRECT_URI = encodeURIComponent('http://192.168.31.204:8080/#/login');
      // const href = location.href;
      // const hasQ = href.indexOf('?') !== -1;
      // // 由于会有页面redirect参数，钉钉扫码返回后会自带问号所以增加DD_code，例DD_code: "?code=d8b7f6eb0a8d3"
      // const REDIRECT_URI = encodeURIComponent(`${href}${hasQ ? '&' : '?'}DD_code=`);
      const query = new URLSearchParams(location.search);
      query.delete('code');
      query.delete('state');
      // query.append('redirect', encodeURIComponent(location.hash));
      const queryString = query.toString();
      const loginredirect = this.getLoginredirect();
      let url = `${location.origin}${location.pathname}`;
      if (queryString) {
        url += `?${queryString}`;
        if (loginredirect) { url += `&loginredirect=${loginredirect}`; }
      } else if (loginredirect) {
        url += `?loginredirect=${loginredirect}`;
      }
      const REDIRECT_URI = encodeURIComponent(url);
      this.ddLoginUrl = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${APPID}&response_type=code&scope=${SCOPE}&state=${STATE}&redirect_uri=${REDIRECT_URI}`;
    },
    changeDDCode(obj) {
      if (this.isInDingTalk || this.isInitCode) {
        return;
      }
      this.isInitCode = true;
      this.createRedirectURI();
      const goto = encodeURIComponent(this.ddLoginUrl);
      window.DDLogin({
        id: obj ? obj.ddId : 'login_dd_code_container', // 这里需要你在自己的页面定义一个HTML标签并设置id
        goto,
        style: 'border: none; background-color: transparent;', // 渲染二维码的区域的样式
        width: '270', // width和height不代表二维码的大小，二维码大小是固定的210px210px。
        height: '320' // 250是钉钉二维码和刷新按钮的最小高度和宽度，保持和login_dd_code_container的宽高一致，方便使login_dd_code_container居中
      });
    },
    onHandleMsg(event) { // main.js中引入的libs/ddLogin.js，会在获取用户扫描之后将获取的loginTmpCode通过window.parent.postMessage(loginTmpCode,'');回调
      const origin = event.origin;
      // 钉钉
      if (origin === 'https://login.dingtalk.com') { // 判断是否来自ddLogin扫码事件。
        const loginTmpCode = event.data; // 拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了
        location.href = `${this.ddLoginUrl}&loginTmpCode=${loginTmpCode}`; // 跳转后钉钉会重定向回REDIRECT_URI，并添加code和state，state对应ddNotLoginState
      }
      // 飞书
      if (this.feishuQRLoginObj && this.feishuQRLoginObj.matchOrigin(origin)) {
        const loginTmpCode = event.data;
        location.href = `${this.feishuLoginUrl}&tmp_code=${loginTmpCode}`;
      }
    },
    autoLogin() {
      this.createRedirectURI('autoLogin');
      location.href = this.ddLoginUrl;
      // openNewWindow(this.ddLoginUrl);
    },
    feishuAutoLogin() {
      if (NODE_ENV === 'development') return;
      this.createFeishuURI(true);
      location.href = this.feishuLoginUrl;
    },
    getLoginredirect() {
      try {
        const loginredirect = this.$route.query.loginredirect;
        return loginredirect || null;
      } catch (error) {
        return null;
      }
    },
    changeFeishuErCode(obj) {
      if (this.isInDingTalk || this.isInitFeishuCode) {
        return;
      }
      const container = document.getElementById(obj ? obj.feishuId : 'login_feishu_code_container');
      if (container.childNodes.length) {
        container.childNodes.forEach(it => {
          container.removeChild(it);
        });
      }
      this.isInitFeishuCode = true;
      this.createFeishuURI();
      this.feishuQRLoginObj = window.QRLogin({
        id: obj ? obj.feishuId : 'login_feishu_code_container',
        goto: this.feishuLoginUrl,
        style: 'border: none; background-color: transparent;',
        width: '260',
        height: '260'
      });
    },
    createFeishuURI(autoLogin = false) {
      const APPID = config.feishuAppId || 'cli_a0683cec1a79900b';
      let STATE = 'feishu-' + new Date().getTime();
      if (autoLogin) {
        STATE += `-autoLogin`;
      }
      localStorage.setItem('ddNotLoginState', STATE);
      const query = new URLSearchParams(location.search);
      query.delete('isFeishu');
      query.delete('code');
      query.delete('state');
      // const queryString = query.toString();
      let url = `${location.origin}`;
      // url = 'http://test.fbcrm.feibo.cc/'; // 测试代码
      url = url.replace(/\/$/, '');
      const queryString = query.toString();
      const loginredirect = this.getLoginredirect();
      if (queryString) {
        url += `?${queryString}`;
        if (loginredirect) { url += `&loginredirect=${loginredirect}`; }
      } else if (loginredirect) {
        url += `?loginredirect=${loginredirect}`;
      }
      const REDIRECT_URI = encodeURIComponent(url);
      localStorage.setItem('CACHE_REDIRECT_URI', url);
      if (autoLogin) { // 免登流程
        this.feishuLoginUrl = `https://open.feishu.cn/open-apis/authen/v1/index?redirect_uri=${REDIRECT_URI}&app_id=${APPID}&state=${STATE}`;
      } else {
        this.feishuLoginUrl = `https://www.feishu.cn/suite/passport/oauth/authorize?client_id=${APPID}&response_type=code&state=${STATE}&redirect_uri=${REDIRECT_URI}`;
      }
    }
  }
};
